﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Web.Script.Services;
using System.IO;
using EntitiesLayer.Entities;
using BusinnesLayer.LogicBusiness;
using System.Data;
using System.ComponentModel;
using Microsoft.Reporting.WebForms;

namespace ClinicaSanPablo
{
    public partial class BusquedaSolicitud : System.Web.UI.Page
    {
        private static Combosbl ptb = new Combosbl();
        private static System.Web.Script.Serialization.JavaScriptSerializer jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string ComboEstadoSolicitud()
        {
            List<Combos> getEstadoSolicitud = ptb.GetAllComboEstadoSolicitud();
            return jsonSerializer.Serialize(getEstadoSolicitud);
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string ComboArea()
        {
            List<Combos> getArea = ptb.GetAllComboArea();
            return jsonSerializer.Serialize(getArea);
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string ComboServicio()
        {
            List<Combos> getServicio = ptb.GetAllComboServicio();
            return jsonSerializer.Serialize(getServicio);
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string ComboPresentacion()
        {
            List<Combos> getPresentacion = ptb.GetAllComboPresentacion();
            return jsonSerializer.Serialize(getPresentacion);
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string ComboUsuario()
        {
            List<Combos> getUsuario = ptb.GetAllComboUsuario();
            return jsonSerializer.Serialize(getUsuario);
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnExportarExcel_Click(object sender, EventArgs e)
        {
            string codigoSolicitud = Request.QueryString["codigoSolicitud"] ?? "";
            string descripcionSolicitud = Request.QueryString["descripcionSolicitud"] ?? "";
            string estadoSolicitud = Request.QueryString["estadoSolicitud"] ?? "";
            string usuarioRegistro = Request.QueryString["usuarioRegistro"] ?? "";
            string areaRegistro = Request.QueryString["areaRegistro"] ?? "";
            string areaInvolucrada = Request.QueryString["areaInvolucrada"] ?? "";
            string servicioInvolucrado = Request.QueryString["servicioInvolucrado"] ?? "";
            string formaPresentacion = Request.QueryString["formaPresentacion"] ?? "";
            string fecha = Request.QueryString["fecha"] ?? "";

            Solicitudbl solBl = new Solicitudbl();
            List<Solicitud> lista = solBl.ConsultarSolicitud(codigoSolicitud, descripcionSolicitud, estadoSolicitud, usuarioRegistro, areaRegistro, areaInvolucrada, servicioInvolucrado, fecha, formaPresentacion);


            if (lista != null && lista.Count > 0)
            {
                this.GridView1.DataSource = lista;
                this.GridView1.DataBind();
                EPrev.Util.GridViewExportUtil.Export("Busqueda_Solicitud.xls", GridView1);

            }

        }

        protected void btnExportarPDF_Click(object sender, EventArgs e)
        {
            try
            {
                DescargarReporteRDLC();
            }
            catch (Exception ex)
            {
                ;
            }
        }
        void DescargarReporteRDLC()
        {
            string codigoSolicitud = Request.QueryString["codigoSolicitud"] ?? "";
            string descripcionSolicitud = Request.QueryString["descripcionSolicitud"] ?? "";
            string estadoSolicitud = Request.QueryString["estadoSolicitud"] ?? "";
            string usuarioRegistro = Request.QueryString["usuarioRegistro"] ?? "";
            string areaRegistro = Request.QueryString["areaRegistro"] ?? "";
            string areaInvolucrada = Request.QueryString["areaInvolucrada"] ?? "";
            string servicioInvolucrado = Request.QueryString["servicioInvolucrado"] ?? "";
            string formaPresentacion = Request.QueryString["formaPresentacion"] ?? "";
            string fecha = Request.QueryString["fecha"] ?? "";

            Solicitudbl solBl = new Solicitudbl();
            List<Solicitud> lista = solBl.ConsultarSolicitud(codigoSolicitud, descripcionSolicitud, estadoSolicitud, usuarioRegistro, areaRegistro, areaInvolucrada, servicioInvolucrado, fecha, formaPresentacion);

            DataTable ds = ConvertTo(lista);

            //...
            ReportViewer1.ProcessingMode = ProcessingMode.Local;
            ReportDataSource datasource = new ReportDataSource("DsReporteGeneral", ds);
            ReportViewer1.LocalReport.DataSources.Clear();
            ReportViewer1.LocalReport.DataSources.Add(datasource);

            List<EntidadUtil> reg = new List<EntidadUtil>();
            reg.Add(new EntidadUtil() { NroRegistros = lista.Count.ToString() });
            ReportDataSource datasource2 = new ReportDataSource("DTTmp", ConvertTo(reg));
            ReportViewer1.LocalReport.DataSources.Add(datasource2);

            ReportViewer1.LocalReport.ReportPath = "reportes/ReporteHistoricoSolicitudes.rdlc";
            ReportViewer1.LocalReport.Refresh();
            ReportViewer1.DataBind();
            AbrirPDF();

        }
        public void AbrirPDF()
        {
            string mimeType;
            string encoding;
            string fileNameExtension;

            Warning[] warnings;
            string[] streams;
            byte[] renderedBytes;

            //Render the report
            renderedBytes = ReportViewer1.LocalReport.Render(
                "pdf",
                null,
                out mimeType,
                out encoding,
                out fileNameExtension,
                out streams,
                out warnings);

            Response.Clear();
            Response.ContentType = "application/pdf";
            Response.AddHeader("Content-disposition", "attachment; filename=Listado.pdf");
            Response.BinaryWrite(renderedBytes);
            Response.End();
        }
        // this is the method I have been using 
        public static DataTable ConvertTo<T>(IList<T> list)
        {
            DataTable table = CreateTable<T>();
            Type entityType = typeof(T);
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);

            foreach (T item in list)
            {
                DataRow row = table.NewRow();

                foreach (PropertyDescriptor prop in properties)
                {
                    row[prop.Name] = prop.GetValue(item);
                }

                table.Rows.Add(row);
            }

            return table;
        }
        public static DataTable CreateTable<T>()
        {
            Type entityType = typeof(T);
            DataTable table = new DataTable(entityType.Name);
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);

            foreach (PropertyDescriptor prop in properties)
            {
                // HERE IS WHERE THE ERROR IS THROWN FOR NULLABLE TYPES 
                table.Columns.Add(prop.Name, prop.PropertyType);
            }

            return table;
        }
    }

    public class EntidadUtil
    {
        public String NroRegistros { get; set; }
    }
}